<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 在数组的原型对象 Array.prototype 上添加一个方法 sum计算数组中所有元素的和
    // reduce 
    Array.prototype.sum = function () {
      return this.reduce((sum, current) => sum + current, 0)
    }

    // for循环
    Array.prototype.sum = function () {
      let sum = 0
      for (let i = 0; i < this.length; i++) {
        sum += this[i]
      }
      return sum
    }

    // foreach 
    Array.prototype.sum = function () {
      let sum = 0
      this.forEach(item => {
        sum += item
      })
      return sum
    }


    const arr = [1, 2, 3, 4, 5]
    console.log(arr.sum())
  </script>
</body>

</html>